// ignore_for_file: use_build_context_synchronously

import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/user.dart';
import 'package:flutter_house_manager/controller/user_info_controller.dart';
import 'package:flutter_house_manager/utils/Emitter.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:get/get.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key, required this.currentIndex});

  final int currentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // Map<String, dynamic> userInfo = {
  //   'id': '',
  //   'nickName': '',
  //   'avatar': '',
  // };

  // 1. 把实例加入共享
  UserInfoController controller = Get.put(UserInfoController());

  // 获取用户信息
  getUserInfo() async {
    final res = await getUserInfoAPI();
    // userInfo = res;
    // 2. 调用控制器的方法更新数据
    controller.updateUserInfo(res);
    // setState(() {});
  }

  // 接收登录成功的事件通知
  registerEvent() {
    eventBus.on<LoginSuccessEvent>().listen((event) {
      getUserInfo();
    });
  }

  // 退出登录
  logout() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: const Text('温馨提示'),
              content: const Text('确定要退出登录吗？'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(); // 关闭对话框
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () async {
                    // 1. 退出登录
                    await tokenManager.removeToken();
                    Navigator.of(context).pop(); // 关闭对话框
                    // 2. 跳转到登录页面
                    Navigator.of(context).pushNamed('/login');
                  },
                  child: const Text(
                    '确定',
                    style: TextStyle(color: Colors.red),
                  ),
                ),
              ]);
        });
  }

  // --------------------------------------------
  @override
  void initState() {
    super.initState();
    registerEvent();
  }

  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 1. 判断当前页面是否是我的
    if (widget.currentIndex == 1) {
      getUserInfo();
    }
  }
  // --------------------------------------------

  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserInfoController>(
      builder: (controller) {
        return Scaffold(
          backgroundColor: const Color(0xFF78B1C5),
          body: SafeArea(
            top: false, // 让背景色侵入顶部安全区域
            child: Column(
              children: [
                // 添加一个标题区域，替代AppBar
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(
                    top: MediaQuery.of(context).padding.top +
                        10, // 状态栏高度 + 额外padding
                    bottom: 10,
                  ),
                  color: const Color(0xFF78B1C5),
                  child: const Center(
                    child: Text(
                      "我的",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
                _buildHeaderSection(),
                _buildFunctionList(),
                _buildBottom()
              ],
            ),
          ),
        );
      },
    );
  }

  // 构建头部信息区域
  Widget _buildHeaderSection() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
      color: const Color(0xFF78B1C5),
      child: Row(
        children: [
          // 头像
          ClipRRect(
              borderRadius: BorderRadius.circular(25), child: getUserAvatar()),
          const SizedBox(width: 15),
          // 用户名
          Text(
            getUserName(),
            style: const TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Spacer(),
          // 完善信息按钮
          GestureDetector(
            onTap: () {
              // 完善信息点击事件
              Navigator.pushNamed(context, '/profile');
            },
            child: const Row(
              children: [
                Text(
                  '完善信息',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                ),
                Icon(
                  Icons.chevron_right,
                  color: Colors.white,
                  size: 20,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建功能列表区域
  Widget _buildFunctionList() {
    return Container(
      margin: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          _buildFunctionItem(
            icon: 'assets/images/house_profile_icon@2x.png',
            title: '我的房屋',
            onTap: () {
              // 我的房屋点击事件
            },
          ),
          const Divider(
            height: 1,
            indent: 10,
            endIndent: 10,
          ),
          _buildFunctionItem(
            icon: 'assets/images/repair_profile_icon@2x.png',
            title: '我的报修',
            onTap: () {
              // 我的报修点击事件
            },
          ),
          const Divider(
            height: 1,
            indent: 10,
            endIndent: 10,
          ),
          _buildFunctionItem(
            icon: 'assets/images/visitor_profile_icon@2x.png',
            title: '访客记录',
            onTap: () {
              // 访客记录点击事件
            },
          ),
        ],
      ),
    );
  }

  // 构建单个功能项
  Widget _buildFunctionItem(
      {required String icon,
      required String title,
      required VoidCallback onTap}) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
        child: Row(
          children: [
            Image.asset(
              icon,
              width: 24,
              height: 24,
            ),
            const SizedBox(width: 15),
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                color: Colors.black87,
              ),
            ),
            const Spacer(),
            const Icon(
              Icons.chevron_right,
              color: Colors.grey,
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  /// 返回用户头像
  getUserAvatar() {
    if (controller.userInfo['avatar'] != '' &&
        controller.userInfo['avatar'] != null) {
      return Image.network(
        controller.userInfo['avatar'],
        width: 50,
        height: 50,
        fit: BoxFit.cover,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 50,
      height: 50,
      fit: BoxFit.cover,
    );
  }

  /// 返回用户名
  getUserName() {
    if (controller.userInfo['nickName'] != '' &&
        controller.userInfo['nickName'] != null) {
      return controller.userInfo['nickName'];
    }
    return '默认用户';
  }

  /// 退出登录
  Widget _buildBottom() {
    if ((controller.userInfo["id"] as String).isEmpty) {
      return const SizedBox(height: 0);
    }
    return SizedBox(
      height: 60,
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
              onTap: () {
                // 退出登录
                logout();
              },
              child: const Text(
                "退出",
                style: TextStyle(color: Colors.red, fontSize: 18),
              )),
        ],
      ),
    );
  }
}
